package org.jeecgframework.web.controller;
import java.io.IOException;
import java.text.CollationKey;
import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mybatis.ext.WiseCoreService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.hibernate.qbc.HqlQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.workflow.common.WorkFlowGlobals;
import org.jeecgframework.workflow.pojo.activiti.ActHiTaskinst;
import org.jeecgframework.workflow.service.ActivitiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
/**
 * @Title: Controller
 * @Description: 采购单表
 * @author onlineGenerator
 * @date 2016-08-03 15:35:40
 * @version V1.0
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsProcurementNoteController")
public class CbsProcurementNoteController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsProcurementNoteController.class);

    @Autowired
    private CbsInvoiceInfoServiceI cbsInvoiceInfoService;

    @Autowired
    private ZyCommonService zyCommonService;

    @Autowired
    private ZyEquipmentSpareServiceI zyEquipmentSpareService;

    @Autowired
    private CbsProcurementNoteServiceI cbsProcurementNoteService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyInspectionPlanServiceI zyInspectionPlanService;
    @Autowired
    private ZyWorkFlowService zyWorkFlowService;
    @Autowired
    private ActivitiService activitiService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ZyPlanRecordServiceI zyPlanRecordService;

    @Autowired
    private CbsQuotationServiceI cbsQuotationService;

    @Autowired
    private WiseCoreService wiseCoreService;


    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 采购单表列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsProcurementNote")
    public ModelAndView cbsProcurementNote(HttpServletRequest request) {

        return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNoteList");
    }
    /**
     * 采购单报价单待办已办列表
     *
     * @return
     */
    @RequestMapping(params = "goProcurementNodeApprovalList")
    public ModelAndView goProcurementNodeApprovalList(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNode-approvalList");
    }

    /**
     * 跳转到委派页面
     *
     * @return
     */
    @RequestMapping(params = "goNodeTransferred")
    public ModelAndView goNodeTransferred(HttpServletRequest request,String taskId,String busId,String instId,String type){

        request.setAttribute("taskId", taskId);
        request.setAttribute("busId", busId);
        request.setAttribute("instId", instId);
        request.setAttribute("type", type);
        String roleCode = StaticValue.CBS_HD_ROLE_CODE;
        if("csa".equals(type) || "appoint".equals(type)){
            roleCode = StaticValue.RULE_CODE_BARCO_CSA;
        }
        /*if("appoint".equals(type)){
            roleCode += "','"+StaticValue.RULE_CODE_BARCO_CSA;
        }*/
        List<TSRoleUser> roleUser = systemService.findHql("from TSRoleUser where TSRole.roleCode in('"+roleCode+"')");

        request.setAttribute("roleUser", roleUser);
        request.setAttribute("currentUser",ResourceUtil.getSessionUserName().getUserName());
        return new ModelAndView("com/zybk/cbs_curement_note/transferred");
    }

    /**
     * 检查设备是否为横店 中影 其他
     * @param busId
     * @return z、h、n | z=中影 h=横店 n=其他
     */
    @ResponseBody
    @RequestMapping(params="getEsDepart")
    public String getEsDepart(String busId){
        TSUser currentUser = ResourceUtil.getSessionUserName(); //判断当前人是否是CSA，如果是CSA，不做校验
        List<TSRoleUser> roleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", currentUser.getId());
        List<String> userRoleCodeList = new ArrayList<String>();
        for (TSRoleUser tsRoleUser : roleUsers) {
            userRoleCodeList.add(tsRoleUser.getTSRole().getRoleCode());
        }
        if(userRoleCodeList.contains(StaticValue.RULE_CODE_BARCO_CSA)){
            return "n";
        }else{
            CbsProcurementNoteEntity note = systemService.get(CbsProcurementNoteEntity.class,busId);
            if(note.getPaertEsList().size() > 0){
                return cbsQuotationService.canReportQuotationByHd(note) ? "n" : "z";
                //			return cbsQuotationService.getEsDepart(note.getPaertEsList().get(0).getEquipmentSpare());
            }
        }

        return "n";
    }


    /**
     * 跳转到驳回意见页面
     *
     * @return
     */
    @RequestMapping(params = "goRejectPage")
    public ModelAndView goRejectPage(HttpServletRequest request,String url){
        request.setAttribute("url", url.replace("-", "&"));
        return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNode-rejectContent");
    }


    /**
     * 进行委派操作
     * @param taskId 节点id
     * @param request
     * @return
     */
    @RequestMapping(params = "reassign")
    @ResponseBody
    public AjaxJson reassign(HttpServletRequest request,String taskId,String userName,String busId,String instId,String content) {
        AjaxJson j = new AjaxJson();
        String type = oConvertUtils.getString(request.getParameter("type"));
        String currentUserName = ResourceUtil.getSessionUserName().getUserName();
        if("csa".equals(type)){
            CbsProcurementNoteEntity note = cbsQuotationService.get(CbsProcurementNoteEntity.class,busId);
            CbsQuotationEntity quotation = cbsQuotationService.createQuotation(note,"2");
            quotation.setCreateBy(userName);
            List<TSBaseUser> toUser = systemService.findHql("from TSBaseUser where userName=?",userName);
            if(toUser.size() > 0){
                quotation.setCreateName(toUser.get(0).getRealName());
            }
            quotation.setCreateDate(new Date());
            //签收
            taskService.claim(taskId, currentUserName);
            zyWorkFlowService.processComplete("2", instId, currentUserName,"0" , "flag");

            Map<String, Object> map = new HashMap<String, Object>();
            ProcessInstance inst = zyWorkFlowService.startOnlineProcess("cbs_quotation", quotation.getId(), map);
            message = ResourceUtil.getSessionUserName().getRealName()+"发送给CSA报价";
            systemService.saveOrUpdate(quotation);
            note.setState("2");
            systemService.saveOrUpdate(note);
            Task task = taskService.createTaskQuery().processInstanceId(inst.getProcessInstanceId()).active().singleResult();
            taskService.claim(task.getId(),userName);
            zyPlanRecordService.savePlanRecord(note.getId(), inst.getProcessInstanceId(), task.getId(), "", currentUserName, message);

        }else{
            message = "转派给"+userName+"成功";
            List<TSUser> toUser = systemService.findByProperty(TSUser.class,"userName",userName);
            try {
                TSUser user = ResourceUtil.getSessionUserName();
                Task  task = activitiService.getTask(taskId);
                zyWorkFlowService.processComplete("1", instId, "", "", "");
                Task taskNext = taskService.createTaskQuery().processInstanceId(instId).active().singleResult();
                taskService.claim(taskNext.getId(),userName);
                CbsInspectionAppointmentEntity appointmentEntity = systemService.get(CbsInspectionAppointmentEntity.class,busId);
                if(StringUtil.isNotEmpty(task.getAssignee()) && !task.getAssignee().equals(user.getUserName())){
                    message = "转派失败,当前办理人已经转派给"+task.getAssignee();
                }else{
                    appointmentEntity.setStatus("4");
                    systemService.saveOrUpdate(appointmentEntity);
                    /*taskService.setOwner(task.getId(), currentUserName);
                    taskService.setAssignee(task.getId(), currentUserName);*/
                    if(oConvertUtils.isNotEmpty(content) && !"null".equals(content)){
                        content = "转派原因："+content;
                    }else{
                        content = "";
                    }
                    if(toUser.size() > 0){
                        content = "转派给："+toUser.get(0).getRealName()+"。"+content;
                    }
                }
                zyPlanRecordService.savePlanRecord(busId, instId, taskId, "", currentUserName, content);
            } catch (Exception e) {
                e.printStackTrace();
                message = "转派给"+userName+"失败";
            }
        }

        j.setMsg(message);
        return j;
    }


    /**
     * 检查task是否已经被办理
     * @return
     */
    @RequestMapping(params="checkTaskHandle")
    @ResponseBody
    public AjaxJson checkTaskHandle(String taskId){
        AjaxJson j = new AjaxJson();
        message = "y";
        try {
            if(StringUtil.isNotEmpty(taskId)){
                message = zyWorkFlowService.checkTaskHandle(taskId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        j.setMsg(message);
        return j;
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "getProcurementNodeApprovalList")
    public void getProcurementNodeApprovalList(VprocurementTask vprocurementTask,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        param.put("assignee",ResourceUtil.getSessionUserName().getUserName());
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }
        if(!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))){
            param.put("createDate_begin",oConvertUtils.getString(param.get("createDate_begin"))+" 01:00:00");
        }
        if(!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))){
            param.put("createDate_end",oConvertUtils.getString(param.get("createDate_end"))+" 23:59:59");
        }
        wiseCoreService.selectDataGrid("selectNoteTask",param,dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }



    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsProcurementNoteEntity cbsProcurementNote,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsProcurementNoteEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsProcurementNote, request.getParameterMap());
        try{
            //自定义追加查询条件
            String query_warranty_begin = request.getParameter("warranty_begin");
            String query_warranty_end = request.getParameter("warranty_end");
            if(StringUtil.isNotEmpty(query_warranty_begin)){
                cq.ge("warranty", new SimpleDateFormat("yyyy-MM-dd").parse(query_warranty_begin));
            }
            if(StringUtil.isNotEmpty(query_warranty_end)){
                cq.le("warranty", new SimpleDateFormat("yyyy-MM-dd").parse(query_warranty_end));
            }
        }catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsProcurementNoteService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 采购单表新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(HttpServletRequest req,String id) {
//        req.setAttribute("defaultGenre",StaticValue.DIC_INVOICE_GENRE_DEDICATED);
        if (StringUtil.isNotEmpty(id)) {
            CbsProcurementNoteEntity cbsProcurementNote = cbsProcurementNoteService.getEntity(CbsProcurementNoteEntity.class,id);
            if(cbsProcurementNote.getInvoice() != null){
                String invoiceId = cbsProcurementNote.getInvoice().getId();
//                if(cbsProcurementNote.getInvoice().getInvoiceGenre().equals(StaticValue.DIC_INVOICE_GENRE_ORDINARY)){
//                    req.setAttribute("ordInvoiceId",invoiceId);
//                }else{
//                    req.setAttribute("dedInvoice",invoiceId);
//                }
                req.setAttribute("defaultGenre",cbsProcurementNote.getInvoice().getInvoiceGenre());
                req.setAttribute("makeInvoice",1);
            }else{
                req.setAttribute("makeInvoice",0);
            }

            req.setAttribute("bus", cbsProcurementNote);
        }
        return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNote-add");
    }

    /**
     * 跳转到是否需要CSA报价审批页面
     * @param request
     * @param taskId 节点Id
     * @param instId 实例Id
     * @param busId 业务Id
     * @return
     */
    @RequestMapping(params="goApproval")
    public ModelAndView goApproval(HttpServletRequest request,String taskId,String instId,String busId,String isDetail){
        CbsProcurementNoteEntity bus = systemService.get(CbsProcurementNoteEntity.class, busId);
        if(StringUtil.isEmpty(isDetail)){
            for(CbsQuotationEntity quo : bus.getQuotationList()){
                if(!"2".equals(quo.getType()) && StringUtil.isNotEmpty(quo.getPdfUrl())){
                    ModelAndView mv = new ModelAndView("redirect:cbsQuotationController.do?goApproval&taskId=" + taskId +"&busId=" + quo.getId() + "&instId=" + instId);
                    return mv;
                }
            }
        }

        request.setAttribute("bus", bus);
        Task task = activitiService.getTask(taskId);
        request.setAttribute("task", task);
        request.setAttribute("instId", instId);
        request.setAttribute("isDetail", isDetail);
        List<ZyPlanRecordEntity> recordList = systemService.findHql("from ZyPlanRecordEntity where busId = ? order by createDate desc", busId);
        request.setAttribute("recordList", recordList);
        if("2".equals(isDetail)){
            for(CbsQuotationEntity quotation : bus.getQuotationList()){
                if("2".equals(quotation.getType())){
                    List<TSRoleUser> roleUsers = systemService.findHql("from TSRoleUser where TSUser.userName=?",ResourceUtil.getSessionUserName().getUserName());
                    for(TSRoleUser ru : roleUsers){
                        if(StaticValue.CBS_HD_ROLE_CODE.equals(ru.getTSRole().getRoleCode())){
                            request.setAttribute("csa","csa");
                            break;
                        }
                    }
                }
            }
            return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNote-approval");
        }
        if("taskNode1".equals(task.getTaskDefinitionKey())){
            return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNote-approval");
        }else if("taskNode2".equals(task.getTaskDefinitionKey())){
            List<CbsQuotationEntity> quotationList = systemService.findHql("from CbsQuotationEntity where note.id = ?", bus.getId());
            if(quotationList.size() > 0){
                request.setAttribute("quotation", quotationList.get(0));
                return new ModelAndView("com/zybk/cbs_quotation/cbsQuotation-edit");
            }

        }
        return null;
    }

    /**
     * 检查设备是否是一个bpNo   是否都在保期 或 都在不保期
     * 1:选择的设备所属BP不一致
     * 2:选择的设备中存在在保和不在保的
     * 2:选择的设备中存在在保和不在保的
     * @param esIdStr
     * @return
     */
    @RequestMapping(params = "inspectEquipment")
    @ResponseBody
    public String inspectEquipment(String esIdStr){
        esIdStr = esIdStr.replace(",", "','");
        List<ZyEquipmentSpareEntity> esList = systemService.findHql("from ZyEquipmentSpareEntity where id in('"+esIdStr+"')");
        if(esList.size() == 1){
            return "0";
        }
        String depart = "",type = "";
        for (ZyEquipmentSpareEntity es : esList) {
            if(StringUtil.isEmpty(es.getId())){
                continue;
            }
            if(StringUtil.isEmpty(depart)){
                depart = zyEquipmentSpareService.checkBP(es.getBpNo());
//				depart = cbsQuotationService.getEsDepart(es);
            }else if(!depart.equals(zyEquipmentSpareService.checkBP(es.getBpNo()))){
                return "1";
            }
            if(StringUtil.isEmpty(type)){
                if(!StringUtil.isNotEmpty(es.getRepairEndDate())){
                    type = "0";
                }else if(es.getRepairEndDate().getTime() < new Date().getTime()){
                    type = "1";
                }else if(es.getRepairEndDate().getTime() > new Date().getTime()){
                    type = "2";
                }
            }else if(!StringUtil.isNotEmpty(es.getRepairEndDate()) && !type.equals("0")){
                return "2";
            }else if(StringUtil.isNotEmpty(es.getRepairEndDate()) && es.getRepairEndDate().getTime() < new Date().getTime() && !type.equals("1")){
                return "2";
            }else if(StringUtil.isNotEmpty(es.getRepairEndDate()) && es.getRepairEndDate().getTime() > new Date().getTime() && !type.equals("2")){
                return "2";
            }
        }


        return "0";
    }

    /**
     * 添加采购单表
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsProcurementNoteEntity cbsProcurementNote, String invoiceId,
                          HttpServletRequest request,
                          String partIdStr,String partCount,String equipmentIdStr,int makeInvoice) {
        AjaxJson j = new AjaxJson();
        message = "采购单创建成功";
        try{
            if("0".equals(cbsProcurementNote.getClientType())){
                cbsProcurementNote.setProcurement(null);
            }
            if(makeInvoice == 1){
                //根据采购单客户类型 更新发票信息
                cbsProcurementNoteService.handleNoteInvoice(cbsProcurementNote,invoiceId);
            }else{
                cbsProcurementNote.setInvoice(null);
            }
            /*是否上门服务*/
            if(StringUtil.isEmpty(cbsProcurementNote.getIsOnsiteServices())){
                cbsProcurementNote.setIsOnsiteServices("0");
            }
            /*来源 1.PC 2.微信,3：未注册用户或银牌用户 */
            cbsProcurementNote.setSource("1");
            if(StringUtil.isNotEmpty(cbsProcurementNote.getId())){
                CbsProcurementNoteEntity t = systemService.get(CbsProcurementNoteEntity.class, cbsProcurementNote.getId());
                MyBeanUtils.copyBeanNotNull2Bean(cbsProcurementNote, t);
                if(makeInvoice != 1){
                    t.setInvoice(null);
                }
                systemService.saveOrUpdate(t);
                systemService.deleteAllEntitie(t.getPaertEsList());  /*设备*/
                systemService.deleteAllEntitie(t.getPartList());   /*零件*/
            }else{
                //设置订单号
                cbsProcurementNote.setProcurementNo(cbsProcurementNoteService.genProcurementNo());
                systemService.save(cbsProcurementNote);
            }

            String partIds[] = partIdStr.split(",");
            String partCounts[] = partCount.split(",");
            String equipmentIds[] = equipmentIdStr.split(",");

            String bpType = "";
            List<CbsProcurementPartEsEntity> partEsList = new ArrayList<CbsProcurementPartEsEntity>();
            for (String id : equipmentIds) {  /*采购单设备*/
                CbsProcurementPartEsEntity partEs = new CbsProcurementPartEsEntity();
                partEs.setProcurementNoteId(cbsProcurementNote.getId());
                ZyEquipmentSpareEntity eq = systemService.get(ZyEquipmentSpareEntity.class, id);
                if (StringUtil.isEmpty(bpType) && eq != null) {
                    bpType = zyEquipmentSpareService.checkBP(eq.getBpNo());
                }
                partEs.setEquipmentSpare(eq);
                partEsList.add(partEs);
            }

            List<CbsProcurementPartEntity> partList = new ArrayList<CbsProcurementPartEntity>();
            for (int i =0;i<partIds.length;i++) {  /*采购单零件表*/
                CbsProcurementPartEntity part = new CbsProcurementPartEntity();
                part.setNum(partCounts[i]);
                part.setPartInfo(systemService.get(CbsPartInfoEntity.class, partIds[i]));
                part.setProcurement(cbsProcurementNote);
                cbsProcurementNoteService.setPartPriceWithType(part,bpType);
                partList.add(part);
            }

            TSUser user = ResourceUtil.getSessionUserName();
            systemService.batchSave(partList);
            systemService.batchSave(partEsList);
            //state = 3 = 取消
            if("3".equals(cbsProcurementNote.getState())){
                message = "采购单取消成功";
            }else if("4".equals(cbsProcurementNote.getState())){
                //草稿
                message = "采购单保存成功";
            }else{
                /*启动采购单流程*/
                ProcessInstance inst = zyWorkFlowService.startOnlineProcess("cbs_procurement_note", cbsProcurementNote.getId(), new HashMap<String, Object>());
                zyWorkFlowService.goProcessNode(cbsProcurementNote.getId(), StaticValue.CBS_PART_FLOW_KEY, "taskNode0", "taskNode1");
                Task task = taskService.createTaskQuery().processInstanceId(inst.getProcessInstanceId()).active().singleResult();
                taskService.claim(task.getId(), user.getUserName());  //签收，当前登录人
                /*采购单日志保存*/
                zyPlanRecordService.savePlanRecord(cbsProcurementNote.getId(), inst.getProcessInstanceId(), task.getId(), "", user.getUserName(), "发起");
            }
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }catch(Exception e){
            e.printStackTrace();
            message = "采购单创建失败";
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 采购单表编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsProcurementNoteEntity cbsProcurementNote, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsProcurementNote.getId())) {
            cbsProcurementNote = cbsProcurementNoteService.getEntity(CbsProcurementNoteEntity.class, cbsProcurementNote.getId());
            req.setAttribute("cbsProcurementNotePage", cbsProcurementNote);
        }
        return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNote-update");
    }

    /**
     * 更新采购单表
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsProcurementNoteEntity cbsProcurementNote, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "采购单表更新成功";
        CbsProcurementNoteEntity t = cbsProcurementNoteService.get(CbsProcurementNoteEntity.class, cbsProcurementNote.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(cbsProcurementNote, t);
            cbsProcurementNoteService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "采购单表更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }



    /**
     * 删除采购单表
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsProcurementNoteEntity cbsProcurementNote, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsProcurementNote = systemService.getEntity(CbsProcurementNoteEntity.class, cbsProcurementNote.getId());
        message = "采购单表删除成功";
        try{
            cbsProcurementNoteService.delete(cbsProcurementNote);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        }catch(Exception e){
            e.printStackTrace();
            message = "采购单表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除采购单表
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids,HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        message = "采购单表删除成功";
        try{
            for(String id:ids.split(",")){
                CbsProcurementNoteEntity cbsProcurementNote = systemService.getEntity(CbsProcurementNoteEntity.class,
                        id
                );
                cbsProcurementNoteService.delete(cbsProcurementNote);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        }catch(Exception e){
            e.printStackTrace();
            message = "采购单表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNoteUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsProcurementNoteEntity cbsProcurementNote,HttpServletRequest request,HttpServletResponse response
            , DataGrid dataGrid,ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CbsProcurementNoteEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsProcurementNote, request.getParameterMap());
        List<CbsProcurementNoteEntity> cbsProcurementNotes = this.cbsProcurementNoteService.getListByCriteriaQuery(cq,false);
        modelMap.put(NormalExcelConstants.FILE_NAME,"采购单表");
        modelMap.put(NormalExcelConstants.CLASS,CbsProcurementNoteEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("采购单表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST,cbsProcurementNotes);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }
    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsProcurementNoteEntity cbsProcurementNote,HttpServletRequest request,HttpServletResponse response
            , DataGrid dataGrid,ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "采购单表");
        modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA,null);
        modelMap.put(TemplateExcelConstants.CLASS,CbsProcurementNoteEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA,null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsProcurementNoteEntity> listCbsProcurementNoteEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),CbsProcurementNoteEntity.class,params);
                for (CbsProcurementNoteEntity cbsProcurementNote : listCbsProcurementNoteEntitys) {
                    cbsProcurementNoteService.save(cbsProcurementNote);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            }finally{
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }



    /**
     * @author xiul
     * 2016-3-30 下午4:53:44
     * Description 新建巡检计划页 选择巡检负责人弹出页
     * @param request
     * @return
     */
    @RequestMapping(params="zyChooseContactersList")
    public ModelAndView zyChooseContactersList(HttpServletRequest request,String company){
        request.setAttribute("company", "&roleCode="+company);
        request.setAttribute("cinemaId",oConvertUtils.getString(request.getParameter("cinemaId")));
        return new ModelAndView("com/zybk/zy_inspection_plan/zyChooseContactersList");
    }

    /**
     * 根据影院查询订单
     */
    @RequestMapping(params = "goNoteList")
    public String getNoteList(ModelMap modelMap,HttpServletRequest request){
        String toUrl = "com/wx/personal_center/order/order_list";
        TSUser user = ResourceUtil.getSessionUserName();
        try{
            List<CbsProcurementNoteEntity> notes = new ArrayList<CbsProcurementNoteEntity>();
            if(null != user && user.ifGoldMedal()){
                notes =cbsProcurementNoteService.findProcurementByContactCinema(ResourceUtil.getSessionUserName().getUserName());
            }else{
                notes =  cbsProcurementNoteService.findHql("from CbsProcurementNoteEntity where createBy=? order by state asc,createDate desc",oConvertUtils.getString(request.getSession().getAttribute("openId")));
                toUrl = "com/wx/personal_center/order/order_list_open";
            }
            List<CbsProcurementNoteEntity> results = new ArrayList<CbsProcurementNoteEntity>();
            for (CbsProcurementNoteEntity note : notes) {
                if(!"4".equals(note.getState())){
                    results.add(note);
                    note.setTotalPrice(0.0);
                    for(CbsProcurementPartEntity part : note.getPartList()){
                        note.setTotalPrice(note.getTotalPrice()+(part.getPrice()*oConvertUtils.getInt(part.getNum())));
                    }
                }

            }
            modelMap.put("notes",results);
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return toUrl;
    }
    /*填写收款时间*/
    @RequestMapping(params = "goThering")
    public ModelAndView gaThering(HttpServletRequest req) {
        String id = req.getParameter("id");
        req.setAttribute("id",id);
        return new ModelAndView("com/zybk/cbs_curement_note/gathering");
    }
    /*由CSA点击“收款”弹出选择收款时间，变更状态为已收款，并记录操作日志。*/
    @RequestMapping(params = "makeCollections")
    @ResponseBody
    public AjaxJson makeCollections(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        String id = req.getParameter("id");
        String gatheringTime = req.getParameter("gatheringTime");
        systemService.updateBySqlString("update cbs_procurement_note set gathering_time = '" + gatheringTime + "',state ='6' where id = '" + id + "'");
        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity();
        zyPlanRecord.setBusId(id);
        TSUser tsUser = ResourceUtil.getSessionUserName();
        zyPlanRecord.setTsUser(tsUser);
        zyPlanRecord.setRemark("选择收款时间"+gatheringTime+",并变更状态为已收款");
        systemService.save(zyPlanRecord);
        return j;
    }

    /*取消，并记录操作日志。*/
    @RequestMapping(params = "cancle")
    @ResponseBody
    public AjaxJson cancle(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        String id = req.getParameter("id");
        String procumentNo = req.getParameter("procumentNo");
        systemService.updateBySqlString("update cbs_procurement_note set state ='3' where id = '" + id + "'");
        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity();
        zyPlanRecord.setBusId(id);
        TSUser tsUser = ResourceUtil.getSessionUserName();
        zyPlanRecord.setTsUser(tsUser);
        zyPlanRecord.setRemark("采购单"+procumentNo+"已取消");
        systemService.save(zyPlanRecord);
        return j;
    }
}
